#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Python 3.x
Flask 2.1.3
Flask-SQLAlchemy 2.5.1

Official Manual Address : https://flask-sqlalchemy.palletsprojects.com/en/2.x/

"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from constants import DB_URI

# Flask初始化
app = Flask(__name__)
# 设置数据库链接
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
# 组件初始化
db = SQLAlchemy(app)


# ORM类
class User(db.Model):
    """
    用户表数据模型
    """
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

        def __repr__(self):
            return '<User %s>' % self.username


# 映射模型到数据库表
db.create_all()


@app.route("/add_data")
def add_data():
    """
    添加数据
    :return:
    """
    admin = User('admin', 'admin@example.com')
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()
    return "ADD DATA"


@app.route("/select_data")
def select_data():
    """
    查询数据
    :return: 
    """
    users = User.query.all()
    print(users)
    # 或
    admin = User.query.filter_by(username='admin').first()
    print(admin)
    # 或
    admin = User.query.filter(User.username == 'admin').first()
    print(admin)
    return "SELECT DATA"


@app.route("/delete_data")
def delete_data():
    """
    删除数据
    :return:
    """
    admin = User.query.filter(User.username == 'admin').first()
    db.session.delete(admin)
    db.session.commit()
    return "DELETE DATA"


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
